<?php $GLOBALS['_beginTime'] = microtime(TRUE); defined('ROOT_PATH') or define('ROOT_PATH','E:\\Workspaces\\xampp\\htdcos\\beebuy'); defined('THINK_PATH') or define('THINK_PATH','./includes/thinkphp/'); defined('APP_NAME') or define('APP_NAME','admin'); defined('APP_PATH') or define('APP_PATH','./admin/'); defined('MEMORY_LIMIT_ON') or define('MEMORY_LIMIT_ON',true); defined('RUNTIME_PATH') or define('RUNTIME_PATH','./admin/Runtime/'); defined('APP_DEBUG') or define('APP_DEBUG',false); defined('RUNTIME_FILE') or define('RUNTIME_FILE','./admin/Runtime/~runtime.php'); defined('THINK_VERSION') or define('THINK_VERSION','3.0'); defined('THINK_RELEASE') or define('THINK_RELEASE','20120305'); defined('IS_CGI') or define('IS_CGI',0); defined('IS_WIN') or define('IS_WIN',1); defined('IS_CLI') or define('IS_CLI',0); defined('_PHP_FILE_') or define('_PHP_FILE_','/beebuy/admin.php'); defined('__ROOT__') or define('__ROOT__','/beebuy'); defined('URL_COMMON') or define('URL_COMMON',0); defined('URL_PATHINFO') or define('URL_PATHINFO',1); defined('URL_REWRITE') or define('URL_REWRITE',2); defined('URL_COMPAT') or define('URL_COMPAT',3); defined('CORE_PATH') or define('CORE_PATH','./includes/thinkphp/Lib/'); defined('EXTEND_PATH') or define('EXTEND_PATH','./includes/thinkphp/Extend/'); defined('MODE_PATH') or define('MODE_PATH','./includes/thinkphp/Extend/Mode/'); defined('ENGINE_PATH') or define('ENGINE_PATH','./includes/thinkphp/Extend/Engine/'); defined('VENDOR_PATH') or define('VENDOR_PATH','./includes/thinkphp/Extend/Vendor/'); defined('LIBRARY_PATH') or define('LIBRARY_PATH','./includes/thinkphp/Extend/Library/'); defined('COMMON_PATH') or define('COMMON_PATH','./admin/Common/'); defined('LIB_PATH') or define('LIB_PATH','./admin/Lib/'); defined('CONF_PATH') or define('CONF_PATH','./admin/Conf/'); defined('LANG_PATH') or define('LANG_PATH','./admin/Lang/'); defined('TMPL_PATH') or define('TMPL_PATH','./admin/Tpl/'); defined('HTML_PATH') or define('HTML_PATH','./admin/Html/'); defined('LOG_PATH') or define('LOG_PATH','./admin/Runtime/Logs/'); defined('TEMP_PATH') or define('TEMP_PATH','./admin/Runtime/Temp/'); defined('DATA_PATH') or define('DATA_PATH','./admin/Runtime/Data/'); defined('CACHE_PATH') or define('CACHE_PATH','./admin/Runtime/Cache/'); function G($start,$end='',$dec=4) { static $_info = array(); if(is_float($end)) { $_info[$start] = $end; }elseif(!empty($end)){ if(!isset($_info[$end])) $_info[$end] = microtime(TRUE); return number_format(($_info[$end]-$_info[$start]),$dec); }else{ $_info[$start] = microtime(TRUE); } } function N($key, $step=0) { static $_num = array(); if (!isset($_num[$key])) { $_num[$key] = 0; } if (empty($step)) return $_num[$key]; else $_num[$key] = $_num[$key] + (int) $step; } function parse_name($name, $type=0) { if ($type) { return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name)); } else { return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); } } function require_cache($filename) { static $_importFiles = array(); if (!isset($_importFiles[$filename])) { if (file_exists_case($filename)) { require $filename; $_importFiles[$filename] = true; } else { $_importFiles[$filename] = false; } } return $_importFiles[$filename]; } function file_exists_case($filename) { if (is_file($filename)) { if (IS_WIN && C('APP_FILE_CASE')) { if (basename(realpath($filename)) != basename($filename)) return false; } return true; } return false; } function import($class, $baseUrl = '', $ext='.class.php') { static $_file = array(); $class = str_replace(array('.', '#'), array('/', '.'), $class); if ('' === $baseUrl && false === strpos($class, '/')) { return alias_import($class); } if (isset($_file[$class . $baseUrl])) return true; else $_file[$class . $baseUrl] = true; $class_strut = explode('/', $class); if (empty($baseUrl)) { if ('@' == $class_strut[0] || APP_NAME == $class_strut[0]) { $baseUrl = dirname(LIB_PATH); $class = substr_replace($class, basename(LIB_PATH).'/', 0, strlen($class_strut[0]) + 1); }elseif ('think' == strtolower($class_strut[0])){ $baseUrl = CORE_PATH; $class = substr($class,6); }elseif (in_array(strtolower($class_strut[0]), array('org', 'com'))) { $baseUrl = LIBRARY_PATH; }else { $class = substr_replace($class, '', 0, strlen($class_strut[0]) + 1); $baseUrl = APP_PATH . '../' . $class_strut[0] . '/'.basename(LIB_PATH).'/'; } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; $classfile = $baseUrl . $class . $ext; if (!class_exists(basename($class),false)) { return require_cache($classfile); } } function load($name, $baseUrl='', $ext='.php') { $name = str_replace(array('.', '#'), array('/', '.'), $name); if (empty($baseUrl)) { if (0 === strpos($name, '@/')) { $baseUrl = COMMON_PATH; $name = substr($name, 2); } else { $baseUrl = EXTEND_PATH . 'Function/'; } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; require_cache($baseUrl . $name . $ext); } function vendor($class, $baseUrl = '', $ext='.php') { if (empty($baseUrl)) $baseUrl = VENDOR_PATH; return import($class, $baseUrl, $ext); } function alias_import($alias, $classfile='') { static $_alias = array(); if (is_string($alias)) { if(isset($_alias[$alias])) { return require_cache($_alias[$alias]); }elseif ('' !== $classfile) { $_alias[$alias] = $classfile; return; } }elseif (is_array($alias)) { $_alias = array_merge($_alias,$alias); return; } return false; } function D($name='') { if(empty($name)) return new Model; static $_model = array(); if(isset($_model[$name])) return $_model[$name]; if(strpos($name,'://')) { $name = str_replace('://','/Model/',$name); }else{ $name = C('DEFAULT_APP').'/Model/'.$name; } import($name.'Model'); $class = basename($name.'Model'); if(class_exists($class)) { $model = new $class(); }else { $model = new Model(basename($name)); } $_model[$name] = $model; return $model; } function M($name='', $tablePrefix='',$connection='') { static $_model = array(); if(strpos($name,':')) { list($class,$name) = explode(':',$name); }else{ $class = 'Model'; } if (!isset($_model[$name . '_' . $class])) $_model[$name . '_' . $class] = new $class($name,$tablePrefix,$connection); return $_model[$name . '_' . $class]; } function A($name) { static $_action = array(); if(isset($_action[$name])) return $_action[$name]; if(strpos($name,'://')) { $name = str_replace('://','/Action/',$name); }else{ $name = '@/Action/'.$name; } import($name.'Action'); $class = basename($name.'Action'); if(class_exists($class,false)) { $action = new $class(); $_action[$name] = $action; return $action; }else { return false; } } function R($url,$vars=array()) { $info = pathinfo($url); $action = $info['basename']; $module = $info['dirname']; $class = A($module); if($class) return call_user_func_array(array(&$class,$action),$vars); else return false; } function L($name=null, $value=null) { static $_lang = array(); if (empty($name)) return $_lang; if (is_string($name)) { $name = strtoupper($name); if (is_null($value)) return isset($_lang[$name]) ? $_lang[$name] : $name; $_lang[$name] = $value; return; } if (is_array($name)) $_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER)); return; } function C($name=null, $value=null) { static $_config = array(); if (empty($name)) return $_config; if (is_string($name)) { if (!strpos($name, '.')) { $name = strtolower($name); if (is_null($value)) return isset($_config[$name]) ? $_config[$name] : null; $_config[$name] = $value; return; } $name = explode('.', $name); $name[0] = strtolower($name[0]); if (is_null($value)) return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null; $_config[$name[0]][$name[1]] = $value; return; } if (is_array($name)){ return $_config = array_merge($_config, array_change_key_case($name)); } return null; } function tag($tag, &$params=NULL) { $extends = C('extends.' . $tag); $tags = C('tags.' . $tag); if (!empty($tags)) { if(empty($tags['_overlay']) && !empty($extends)) { $tags = array_unique(array_merge($extends,$tags)); }elseif(isset($tags['_overlay'])){ unset($tags['_overlay']); } }elseif(!empty($extends)) { $tags = $extends; } if($tags) { if(APP_DEBUG) { G($tag.'Start'); Log::record('Tag[ '.$tag.' ] --START--',Log::INFO); } foreach ($tags as $key=>$name) { if(!is_int($key)) { $name = $key; } B($name, $params); } if(APP_DEBUG) { Log::record('Tag[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]',Log::INFO); } }else{ return false; } } function add_tag_behavior($tag,$behavior,$path='') { $array = C('tags.'.$tag); if(!$array) { $array = array(); } if($path) { $array[$behavior] = $path; }else{ $array[] = $behavior; } C('tags.'.$tag,$array); } function filter($name, &$content) { $class = $name . 'Filter'; require_cache(LIB_PATH . 'Filter/' . $class . '.class.php'); $filter = new $class(); $content = $filter->run($content); } function B($name, &$params=NULL) { $class = $name.'Behavior'; G('behaviorStart'); $behavior = new $class(); $behavior->run($params); if(APP_DEBUG) { G('behaviorEnd'); Log::record('Run '.$name.' Behavior [ RunTime:'.G('behaviorStart','behaviorEnd',6).'s ]',Log::INFO); } } function W($name, $data=array(), $return=false) { $class = $name . 'Widget'; require_cache(LIB_PATH . 'Widget/' . $class . '.class.php'); if (!class_exists($class)) throw_exception(L('_CLASS_NOT_EXIST_') . ':' . $class); $widget = Think::instance($class); $content = $widget->render($data); if ($return) return $content; else echo $content; } function strip_whitespace($content) { $stripStr = ''; $tokens = token_get_all($content); $last_space = false; for ($i = 0, $j = count($tokens); $i < $j; $i++) { if (is_string($tokens[$i])) { $last_space = false; $stripStr .= $tokens[$i]; } else { switch ($tokens[$i][0]) { case T_COMMENT: case T_DOC_COMMENT: break; case T_WHITESPACE: if (!$last_space) { $stripStr .= ' '; $last_space = true; } break; case T_START_HEREDOC: $stripStr .= "<<<THINK\n"; break; case T_END_HEREDOC: $stripStr .= "THINK;\n"; for($k = $i+1; $k < $j; $k++) { if(is_string($tokens[$k]) && $tokens[$k] == ';') { $i = $k; break; } else if($tokens[$k][0] == T_CLOSE_TAG) { break; } } break; default: $last_space = false; $stripStr .= $tokens[$i][1]; } } } return $stripStr; } function mk_dir($dir, $mode = 0777) { if (is_dir($dir) || @mkdir($dir, $mode)) return true; if (!mk_dir(dirname($dir), $mode)) return false; return @mkdir($dir, $mode); } class Think { private static $_instance = array(); static public function Start() { set_error_handler(array('Think', 'appError')); set_exception_handler(array('Think', 'appException')); spl_autoload_register(array('Think', 'autoload')); App::run(); return; } public static function autoload($class) { if (alias_import($class)) return; if (substr($class, -8) == 'Behavior') { if (require_cache(CORE_PATH . 'Behavior/' . $class . '.class.php') || require_cache(EXTEND_PATH . 'Behavior/' . $class . '.class.php') || require_cache(LIB_PATH . 'Behavior/' . $class . '.class.php') || (defined('MODE_NAME') && require_cache(MODE_PATH . ucwords(MODE_NAME) . '/Behavior/' . $class . '.class.php'))) { return; } } elseif (substr($class, -5) == 'Model') { if (require_cache(LIB_PATH . 'Model/' . $class . '.class.php') || require_cache(EXTEND_PATH . 'Model/' . $class . '.class.php')) { return; } } elseif (substr($class, -6) == 'Action') { if ((defined('GROUP_NAME') && require_cache(LIB_PATH . 'Action/' . GROUP_NAME . '/' . $class . '.class.php')) || require_cache(LIB_PATH . 'Action/' . $class . '.class.php') || require_cache(EXTEND_PATH . 'Action/' . $class . '.class.php')) { return; } } $paths = explode(',', C('APP_AUTOLOAD_PATH')); foreach ($paths as $path) { if (import($path . '.' . $class)) return; } } static public function instance($class, $method = '') { $identify = $class . $method; if (!isset(self::$_instance[$identify])) { if (class_exists($class)) { $o = new $class(); if (!empty($method) && method_exists($o, $method)) self::$_instance[$identify] = call_user_func_array(array(&$o, $method)); else self::$_instance[$identify] = $o; } else halt(L('_CLASS_NOT_EXIST_') . ':' . $class); } return self::$_instance[$identify]; } static public function appException($e) { halt($e->__toString()); } static public function appError($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_ERROR: case E_USER_ERROR: $errorStr = "[$errno] $errstr " . basename($errfile) . " 第 $errline 行."; if (C('LOG_RECORD')) Log::write($errorStr, Log::ERR); halt($errorStr); break; case E_STRICT: case E_USER_WARNING: case E_USER_NOTICE: default: $errorStr = "[$errno] $errstr " . basename($errfile) . " 第 $errline 行."; Log::record($errorStr, Log::NOTICE); break; } } public function __set($name, $value) { if (property_exists($this, $name)) $this->$name = $value; } public function __get($name) { return isset($this->$name) ? $this->$name : null; } } class ThinkException extends Exception { private $type; private $extra; public function __construct($message,$code=0,$extra=false) { parent::__construct($message,$code); $this->type = get_class($this); $this->extra = $extra; } public function __toString() { $trace = $this->getTrace(); if($this->extra) array_shift($trace); $this->class = $trace[0]['class']; $this->function = $trace[0]['function']; $this->file = $trace[0]['file']; $this->line = $trace[0]['line']; $file = file($this->file); $traceInfo=''; $time = date('y-m-d H:i:m'); foreach($trace as $t) { $traceInfo .= '['.$time.'] '.$t['file'].' ('.$t['line'].') '; $traceInfo .= $t['class'].$t['type'].$t['function'].'('; $traceInfo .= implode(', ', $t['args']); $traceInfo .=")\n"; } $error['message'] = $this->message; $error['type'] = $this->type; $error['detail'] = L('_MODULE_').'['.MODULE_NAME.'] '.L('_ACTION_').'['.ACTION_NAME.']'."\n"; $error['detail'] .= ($this->line-2).': '.$file[$this->line-3]; $error['detail'] .= ($this->line-1).': '.$file[$this->line-2]; $error['detail'] .= '<font color="#FF6600" >'.($this->line).': <strong>'.$file[$this->line-1].'</strong></font>'; $error['detail'] .= ($this->line+1).': '.$file[$this->line]; $error['detail'] .= ($this->line+2).': '.$file[$this->line+1]; $error['class'] = $this->class; $error['function'] = $this->function; $error['file'] = $this->file; $error['line'] = $this->line; $error['trace'] = $traceInfo; if(C('LOG_EXCEPTION_RECORD')) { Log::Write('('.$this->type.') '.$this->message); } return $error ; } } abstract class Behavior { protected $options = array(); public function __construct() { if(!empty($this->options)) { foreach ($this->options as $name=>$val){ if(NULL !== C($name)) { $this->options[$name] = C($name); }else{ C($name,$val); } } array_change_key_case($this->options); } } public function __get($name){ return $this->options[strtolower($name)]; } abstract public function run(&$params); } class ReadHtmlCacheBehavior extends Behavior { protected $options = array( 'HTML_CACHE_ON'=>false, 'HTML_CACHE_TIME'=>60, 'HTML_CACHE_RULES'=>array(), 'HTML_FILE_SUFFIX'=>'.html', ); public function run(&$params){ if(C('HTML_CACHE_ON')) { if(($cacheTime = $this->requireHtmlCache()) && $this->checkHTMLCache(HTML_FILE_NAME,$cacheTime)) { readfile(HTML_FILE_NAME); exit(); } } } static private function requireHtmlCache() { $htmls = C('HTML_CACHE_RULES'); if(!empty($htmls)) { $moduleName = strtolower(MODULE_NAME); if(isset($htmls[$moduleName.':'.ACTION_NAME])) { $html = $htmls[$moduleName.':'.ACTION_NAME]; }elseif(isset($htmls[$moduleName.':'])){ $html = $htmls[$moduleName.':']; }elseif(isset($htmls[ACTION_NAME])){ $html = $htmls[ACTION_NAME]; }elseif(isset($htmls['*'])){ $html = $htmls['*']; }elseif(isset($htmls['empty:index']) && !class_exists(MODULE_NAME.'Action')){ $html = $htmls['empty:index']; }elseif(isset($htmls[$moduleName.':_empty']) && $this->isEmptyAction(MODULE_NAME,ACTION_NAME)){ $html = $htmls[$moduleName.':_empty']; } if(!empty($html)) { $rule = $html[0]; $rule = preg_replace('/{\$(_\w+)\.(\w+)\|(\w+)}/e',"\\3(\$\\1['\\2'])",$rule); $rule = preg_replace('/{\$(_\w+)\.(\w+)}/e',"\$\\1['\\2']",$rule); $rule = preg_replace('/{(\w+)\|(\w+)}/e',"\\2(\$_GET['\\1'])",$rule); $rule = preg_replace('/{(\w+)}/e',"\$_GET['\\1']",$rule); $rule = str_ireplace( array('{:app}','{:module}','{:action}','{:group}'), array(APP_NAME,MODULE_NAME,ACTION_NAME,defined('GROUP_NAME')?GROUP_NAME:''), $rule); $rule = preg_replace('/{|(\w+)}/e',"\\1()",$rule); if(!empty($html[2])) $rule = $html[2]($rule); $cacheTime = isset($html[1])?$html[1]:C('HTML_CACHE_TIME'); define('HTML_FILE_NAME',HTML_PATH . $rule.C('HTML_FILE_SUFFIX')); return $cacheTime; } } return false; } static public function checkHTMLCache($cacheFile='',$cacheTime='') { if(!is_file($cacheFile)){ return false; }elseif (filemtime(C('TEMPLATE_NAME')) > filemtime($cacheFile)) { return false; }elseif(!is_numeric($cacheTime) && function_exists($cacheTime)){ return $cacheTime($cacheFile); }elseif ($cacheTime != 0 && time() > filemtime($cacheFile)+$cacheTime) { return false; } return true; } static private function isEmptyAction($module,$action) { $className = $module.'Action'; $class=new $className; return !method_exists($class,$action); } } class CheckRouteBehavior extends Behavior { protected $options = array( 'URL_ROUTER_ON' => false, 'URL_ROUTE_RULES' => array(), ); public function run(&$return){ $regx = trim($_SERVER['PATH_INFO'],'/'); if(empty($regx)) return $return = true; if(!C('URL_ROUTER_ON')) return $return = false; $routes = C('URL_ROUTE_RULES'); if(!empty($routes)) { $depr = C('URL_PATHINFO_DEPR'); $regx = str_replace($depr,'/',$regx); foreach ($routes as $rule=>$route){ if(0===strpos($rule,'/') && preg_match($rule,$regx,$matches)) { return $return = $this->parseRegex($matches,$route,$regx); }else{ $len1= substr_count($regx,'/'); $len2 = substr_count($rule,'/'); if($len1>=$len2) { if('$' == substr($rule,-1,1)) { if($len1 != $len2) { continue; }else{ $rule = substr($rule,0,-1); } } $match = $this->checkUrlMatch($regx,$rule); if($match) return $return = $this->parseRule($rule,$route,$regx); } } } } $return = false; } private function checkUrlMatch($regx,$rule) { $m1 = explode('/',$regx); $m2 = explode('/',$rule); $match = true; foreach ($m2 as $key=>$val){ if(':' == substr($val,0,1)) { if(strpos($val,'\\')) { $type = substr($val,-1); if('d'==$type && !is_numeric($m1[$key])) { $match = false; break; } }elseif(strpos($val,'^')){ $array = explode('|',substr(strstr($val,'^'),1)); if(in_array($m1[$key],$array)) { $match = false; break; } } }elseif(0 !== strcasecmp($val,$m1[$key])){ $match = false; break; } } return $match; } private function parseUrl($url) { $var = array(); if(false !== strpos($url,'?')) { $info = parse_url($url); $path = explode('/',$info['path']); parse_str($info['query'],$var); }elseif(strpos($url,'/')){ $path = explode('/',$url); }else{ parse_str($url,$var); } if(isset($path)) { $var[C('VAR_ACTION')] = array_pop($path); if(!empty($path)) { $var[C('VAR_MODULE')] = array_pop($path); } if(!empty($path)) { $var[C('VAR_GROUP')] = array_pop($path); } } return $var; } private function parseRule($rule,$route,$regx) { $url = is_array($route)?$route[0]:$route; $paths = explode('/',$regx); $matches = array(); $rule = explode('/',$rule); foreach ($rule as $item){ if(0===strpos($item,':')) { if($pos = strpos($item,'^') ) { $var = substr($item,1,$pos-1); }elseif(strpos($item,'\\')){ $var = substr($item,1,-2); }else{ $var = substr($item,1); } $matches[$var] = array_shift($paths); }else{ array_shift($paths); } } if(0=== strpos($url,'/') || 0===strpos($url,'http')) { if(strpos($url,':')) { $values = array_values($matches); $url = preg_replace('/:(\d)/e','$values[\\1-1]',$url); } header("Location: $url", true,(is_array($route) && isset($route[1]))?$route[1]:301); exit; }else{ $var = $this->parseUrl($url); $values = array_values($matches); foreach ($var as $key=>$val){ if(0===strpos($val,':')) { $var[$key] = $values[substr($val,1)-1]; } } $var = array_merge($matches,$var); if($paths) { preg_replace('@(\w+)\/([^,\/]+)@e', '$var[strtolower(\'\\1\')]="\\2";', implode('/',$paths)); } if(is_array($route) && isset($route[1])) { parse_str($route[1],$params); $var = array_merge($var,$params); } $_GET = array_merge($var,$_GET); } return true; } private function parseRegex($matches,$route,$regx) { $url = is_array($route)?$route[0]:$route; $url = preg_replace('/:(\d)/e','$matches[\\1]',$url); if(0=== strpos($url,'/') || 0===strpos($url,'http')) { header("Location: $url", true,(is_array($route) && isset($route[1]))?$route[1]:301); exit; }else{ $var = $this->parseUrl($url); $regx = substr_replace($regx,'',0,strlen($matches[0])); if($regx) { preg_replace('@(\w+)\/([^,\/]+)@e', '$var[strtolower(\'\\1\')]="\\2";', $regx); } if(is_array($route) && isset($route[1])) { parse_str($route[1],$params); $var = array_merge($var,$params); } $_GET = array_merge($var,$_GET); } return true; } } class LocationTemplateBehavior extends Behavior { public function run(&$templateFile){ if(!file_exists_case($templateFile)) $templateFile = $this->parseTemplateFile($templateFile); } private function parseTemplateFile($templateFile) { if(''==$templateFile) { $templateFile = C('TEMPLATE_NAME'); }elseif(false === strpos($templateFile,C('TMPL_TEMPLATE_SUFFIX'))){ $path = explode(':',$templateFile); $action = array_pop($path); $module = !empty($path)?array_pop($path):MODULE_NAME; if(!empty($path)) { $path = dirname(THEME_PATH).'/'.array_pop($path).'/'; }else{ $path = THEME_PATH; } $depr = defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/'; $templateFile = $path.$module.$depr.$action.C('TMPL_TEMPLATE_SUFFIX'); } if(!file_exists_case($templateFile)) throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$templateFile.']'); return $templateFile; } } class ParseTemplateBehavior extends Behavior { protected $options = array( 'TMPL_ENGINE_TYPE' => 'Think', 'TMPL_CACHFILE_SUFFIX' => '.php', 'TMPL_DENY_FUNC_LIST' => 'echo,exit', 'TMPL_DENY_PHP' =>false, 'TMPL_L_DELIM' => '{', 'TMPL_R_DELIM' => '}', 'TMPL_VAR_IDENTIFY' => 'array', 'TMPL_STRIP_SPACE' => true, 'TMPL_CACHE_ON' => true, 'TMPL_CACHE_TIME' => 0, 'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', 'LAYOUT_ON' => false, 'LAYOUT_NAME' => 'layout', 'TAGLIB_BEGIN' => '<', 'TAGLIB_END' => '>', 'TAGLIB_LOAD' => true, 'TAGLIB_BUILD_IN' => 'cx', 'TAGLIB_PRE_LOAD' => '', ); public function run(&$_data){ $engine = strtolower(C('TMPL_ENGINE_TYPE')); if('think'==$engine){ if($this->checkCache($_data['file'])) { extract($_data['var'], EXTR_OVERWRITE); include C('CACHE_PATH').md5($_data['file']).C('TMPL_CACHFILE_SUFFIX'); }else{ $tpl = Think::instance('ThinkTemplate'); $tpl->fetch($_data['file'],$_data['var']); } }else{ $class = 'Template'.ucwords($engine); if(is_file(CORE_PATH.'Driver/Template/'.$class.'.class.php')) { $path = CORE_PATH; }else{ $path = EXTEND_PATH; } if(require_cache($path.'Driver/Template/'.$class.'.class.php')) { $tpl = new $class; $tpl->fetch($_data['file'],$_data['var']); }else { throw_exception(L('_NOT_SUPPERT_').': ' . $class); } } } protected function checkCache($tmplTemplateFile) { if (!C('TMPL_CACHE_ON')) return false; $tmplCacheFile = C('CACHE_PATH').md5($tmplTemplateFile).C('TMPL_CACHFILE_SUFFIX'); if(!is_file($tmplCacheFile)){ return false; }elseif (filemtime($tmplTemplateFile) > filemtime($tmplCacheFile)) { return false; }elseif (C('TMPL_CACHE_TIME') != 0 && time() > filemtime($tmplCacheFile)+C('TMPL_CACHE_TIME')) { return false; } if(C('LAYOUT_ON')) { $layoutFile = THEME_PATH.C('LAYOUT_NAME').C('TMPL_TEMPLATE_SUFFIX'); if(filemtime($layoutFile) > filemtime($tmplCacheFile)) { return false; } } return true; } } class ContentReplaceBehavior extends Behavior { protected $options = array( 'TMPL_PARSE_STRING'=>array(), ); public function run(&$content){ $content = $this->templateContentReplace($content); } protected function templateContentReplace($content) { $replace = array( '__TMPL__' => APP_TMPL_PATH, '__ROOT__' => __ROOT__, '__APP__' => __APP__, '__GROUP__' => defined('GROUP_NAME')?__GROUP__:__APP__, '__ACTION__' => __ACTION__, '__SELF__' => __SELF__, '__URL__' => __URL__, '../Public' => APP_TMPL_PATH.'Public', '__PUBLIC__' => __ROOT__.'/Public', ); if(is_array(C('TMPL_PARSE_STRING')) ) $replace = array_merge($replace,C('TMPL_PARSE_STRING')); $content = str_replace(array_keys($replace),array_values($replace),$content); return $content; } } class TokenBuildBehavior extends Behavior { protected $options = array( 'TOKEN_ON' => true, 'TOKEN_NAME' => '__hash__', 'TOKEN_TYPE' => 'md5', 'TOKEN_RESET' => true, ); public function run(&$content){ if(C('TOKEN_ON')) { if(strpos($content,'{__TOKEN__}')) { $content = str_replace('{__TOKEN__}',$this->buildToken(),$content); }elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) { $content = str_replace($match[0],$this->buildToken().$match[0],$content); } } } private function buildToken() { $tokenName = C('TOKEN_NAME'); $tokenType = C('TOKEN_TYPE'); if(!isset($_SESSION[$tokenName])) { $_SESSION[$tokenName] = array(); } $tokenKey = md5($_SERVER['REQUEST_URI']); if(isset($_SESSION[$tokenName][$tokenKey])) { $tokenValue = $_SESSION[$tokenName][$tokenKey]; }else{ $tokenValue = $tokenType(microtime(TRUE)); $_SESSION[$tokenName][$tokenKey] = $tokenValue; } if($action = C('TOKEN_ACTION')){ $_SESSION[$action($tokenKey)] = true; } $token = '<input type="hidden" name="'.$tokenName.'" value="'.$tokenKey.'_'.$tokenValue.'" />'; return $token; } } class WriteHtmlCacheBehavior extends Behavior { public function run(&$content){ if(C('HTML_CACHE_ON') && defined('HTML_FILE_NAME')) { if(!is_dir(dirname(HTML_FILE_NAME))) mk_dir(dirname(HTML_FILE_NAME)); if( false === file_put_contents( HTML_FILE_NAME , $content )) throw_exception(L('_CACHE_WRITE_ERROR_').':'.HTML_FILE_NAME); } } } class ShowRuntimeBehavior extends Behavior { protected $options = array( 'SHOW_RUN_TIME' => false, 'SHOW_ADV_TIME' => false, 'SHOW_DB_TIMES' => false, 'SHOW_CACHE_TIMES' => false, 'SHOW_USE_MEM' => false, 'SHOW_LOAD_FILE' => false, 'SHOW_FUN_TIMES' => false , ); public function run(&$content){ if(C('SHOW_RUN_TIME')){ if(false !== strpos($content,'{__NORUNTIME__}')) { $content = str_replace('{__NORUNTIME__}','',$content); }else{ $runtime = $this->showTime(); if(strpos($content,'{__RUNTIME__}')) $content = str_replace('{__RUNTIME__}',$runtime,$content); else $content .= $runtime; } }else{ $content = str_replace(array('{__NORUNTIME__}','{__RUNTIME__}'),'',$content); } } private function showTime() { G('beginTime',$GLOBALS['_beginTime']); G('viewEndTime'); $showTime = 'Process: '.G('beginTime','viewEndTime').'s '; if(C('SHOW_ADV_TIME')) { $showTime .= '( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )'; } if(C('SHOW_DB_TIMES') && class_exists('Db',false) ) { $showTime .= ' | DB :'.N('db_query').' queries '.N('db_write').' writes '; } if(C('SHOW_CACHE_TIMES') && class_exists('Cache',false)) { $showTime .= ' | Cache :'.N('cache_read').' gets '.N('cache_write').' writes '; } if(MEMORY_LIMIT_ON && C('SHOW_USE_MEM')) { $showTime .= ' | UseMem:'. number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024).' kb'; } if(C('SHOW_LOAD_FILE')) { $showTime .= ' | LoadFile:'.count(get_included_files()); } if(C('SHOW_FUN_TIMES')) { $fun = get_defined_functions(); $showTime .= ' | CallFun:'.count($fun['user']).','.count($fun['internal']); } return $showTime; } } class ShowPageTraceBehavior extends Behavior { protected $options = array( 'SHOW_PAGE_TRACE' => false, ); public function run(&$params){ if(C('SHOW_PAGE_TRACE')) { echo $this->showTrace(); } } private function showTrace() { $log = Log::$log; $files = get_included_files(); $trace = array( '请求时间'=> date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']), '当前页面'=> __SELF__, '请求协议'=> $_SERVER['SERVER_PROTOCOL'].' '.$_SERVER['REQUEST_METHOD'], '运行信息'=> $this->showTime(), '会话ID' => session_id(), '日志记录'=> count($log)?count($log).'条日志<br/>'.implode('<br/>',$log):'无日志记录', '加载文件'=> count($files).str_replace("\n",'<br/>',substr(substr(print_r($files,true),7),0,-2)), ); $traceFile = CONF_PATH.'trace.php'; if(is_file($traceFile)) { $trace = array_merge(include $traceFile,$trace); } trace($trace); ob_start(); include C('TMPL_TRACE_FILE')?C('TMPL_TRACE_FILE'):THINK_PATH.'Tpl/page_trace.tpl'; return ob_get_clean(); } private function showTime() { G('beginTime',$GLOBALS['_beginTime']); G('viewEndTime'); $showTime = 'Process: '.G('beginTime','viewEndTime').'s '; $showTime .= '( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )'; if(class_exists('Db',false) ) { $showTime .= ' | DB :'.N('db_query').' queries '.N('db_write').' writes '; } if( class_exists('Cache',false)) { $showTime .= ' | Cache :'.N('cache_read').' gets '.N('cache_write').' writes '; } if(MEMORY_LIMIT_ON ) { $showTime .= ' | UseMem:'. number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024).' kb'; } $showTime .= ' | LoadFile:'.count(get_included_files()); $fun = get_defined_functions(); $showTime .= ' | CallFun:'.count($fun['user']).','.count($fun['internal']); return $showTime; } }alias_import(array ( 'Model' => './includes/thinkphp/Lib/Core/Model.class.php', 'Db' => './includes/thinkphp/Lib/Core/Db.class.php', 'Log' => './includes/thinkphp/Lib/Core/Log.class.php', 'ThinkTemplate' => './includes/thinkphp/Lib/Template/ThinkTemplate.class.php', 'TagLib' => './includes/thinkphp/Lib/Template/TagLib.class.php', 'Cache' => './includes/thinkphp/Lib/Core/Cache.class.php', 'Widget' => './includes/thinkphp/Lib/Core/Widget.class.php', 'TagLibCx' => './includes/thinkphp/Lib/Driver/TagLib/TagLibCx.class.php', )); function halt($error) { $e = array(); if (APP_DEBUG) { if (!is_array($error)) { $trace = debug_backtrace(); $e['message'] = $error; $e['file'] = $trace[0]['file']; $e['class'] = $trace[0]['class']; $e['function'] = $trace[0]['function']; $e['line'] = $trace[0]['line']; $traceInfo = ''; $time = date('y-m-d H:i:m'); foreach ($trace as $t) { $traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') '; $traceInfo .= $t['class'] . $t['type'] . $t['function'] . '('; $traceInfo .= implode(', ', $t['args']); $traceInfo .=')<br/>'; } $e['trace'] = $traceInfo; } else { $e = $error; } include C('TMPL_EXCEPTION_FILE'); } else { $error_page = C('ERROR_PAGE'); if (!empty($error_page)) { redirect($error_page); } else { if (C('SHOW_ERROR_MSG')) $e['message'] = is_array($error) ? $error['message'] : $error; else $e['message'] = C('ERROR_MESSAGE'); include C('TMPL_EXCEPTION_FILE'); } } exit; } function throw_exception($msg, $type = 'ThinkException', $code = 0) { if (class_exists($type, false)) throw new $type($msg, $code, true); else halt($msg); } function dump($var, $echo = true, $label = null, $strict = true) { $label = ($label === null) ? '' : rtrim($label) . ' '; if (!$strict) { if (ini_get('html_errors')) { $output = print_r($var, true); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } else { $output = $label . print_r($var, true); } } else { ob_start(); var_dump($var); $output = ob_get_clean(); if (!extension_loaded('xdebug')) { $output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } } if ($echo) { echo($output); return null; }else return $output; } function debug_start($label = '') { $GLOBALS[$label]['_beginTime'] = microtime(TRUE); if (MEMORY_LIMIT_ON) $GLOBALS[$label]['_beginMem'] = memory_get_usage(); } function debug_end($label = '') { $GLOBALS[$label]['_endTime'] = microtime(TRUE); echo '<div style="text-align:center;width:100%">Process ' . $label . ': Times ' . number_format($GLOBALS[$label]['_endTime'] - $GLOBALS[$label]['_beginTime'], 6) . 's '; if (MEMORY_LIMIT_ON) { $GLOBALS[$label]['_endMem'] = memory_get_usage(); echo ' Memories ' . number_format(($GLOBALS[$label]['_endMem'] - $GLOBALS[$label]['_beginMem']) / 1024) . ' k'; } echo '</div>'; } function trace($title = '', $value = '') { if (!C('SHOW_PAGE_TRACE')) return; static $_trace = array(); if (is_array($title)) { $_trace = array_merge($_trace, $title); } elseif ('' !== $value) { $_trace[$title] = $value; } elseif ('' !== $title) { return $_trace[$title]; } else { return $_trace; } } function layout($layout) { if (false !== $layout) { C('LAYOUT_ON', true); if (is_string($layout)) { C('LAYOUT_NAME', $layout); } } } function U($url,$vars='',$suffix=true,$redirect=false,$domain=false) { $info = parse_url($url); $url = !empty($info['path'])?$info['path']:ACTION_NAME; if($domain===true){ $domain = $_SERVER['HTTP_HOST']; if(C('APP_SUB_DOMAIN_DEPLOY') ) { $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.'); foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) { if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) { $domain = $key.strstr($domain,'.'); $url = substr_replace($url,'',0,strlen($rule[0])); break; } } } } if(is_string($vars)) { parse_str($vars,$vars); }elseif(!is_array($vars)){ $vars = array(); } if(isset($info['query'])) { parse_str($info['query'],$params); $vars = array_merge($params,$vars); } foreach ($vars as $key=>$value){ $vars_norouter[$key]=$value; } if(C('URL_REWIRTE_MODE_VAL')&&C('URL_MODEL') != 0){ foreach($vars as $k=>$v){ $url_vars[] = $v; } $vars = implode("/",$url_vars); } $depr = C('URL_PATHINFO_DEPR'); if($url) { if(0=== strpos($url,'/')) { $route = true; $url = substr($url,1); if('/' != $depr) { $url = str_replace('/',$depr,$url); } }else{ if('/' != $depr) { $url = str_replace('/',$depr,$url); } $url = trim($url,$depr); $path = explode($depr,$url); $var = array(); $var[C('VAR_ACTION')] = !empty($path)?array_pop($path):ACTION_NAME; $var[C('VAR_MODULE')] = !empty($path)?array_pop($path):MODULE_NAME; if(C('URL_CASE_INSENSITIVE')) { $var[C('VAR_MODULE')] = parse_name($var[C('VAR_MODULE')]); } if(C('APP_GROUP_LIST')) { if(!empty($path)) { $group = array_pop($path); $var[C('VAR_GROUP')] = $group; }else{ if(GROUP_NAME != C('DEFAULT_GROUP')) { $var[C('VAR_GROUP')] = GROUP_NAME; } } } } } if(C('URL_MODEL') == 0) { $url = __APP__.'?'.http_build_query($var); if(!empty($vars)) { $vars = http_build_query($vars); $url .= '&'.$vars; } }else{ if(isset($route)) { $url = __APP__.'/'.$url; }else{ $url = __APP__.'/'.implode($depr,array_reverse($var)); } if(C('URL_REWIRTE_MODE_VAL')){ $router_ruler = include ROOT_PATH . '/router.inc.php'; $site_url = implode("/",array_reverse($var)); if($router_ruler[$site_url]){ $url = __APP__.'/'.$router_ruler[$site_url]; $url = rtrim($url.$depr.$vars,$depr); } else{ if(!empty($vars_norouter)){ $vars_norouter = http_build_query($vars_norouter); $url .= $depr.str_replace(array('=','&'),$depr,$vars_norouter); } } } if(!empty($vars) && !C('URL_REWIRTE_MODE_VAL')) { $vars = http_build_query($vars); $url .= $depr.str_replace(array('=','&'),$depr,$vars); } if($suffix){ $suffix = $suffix===true?C('URL_HTML_SUFFIX'):$suffix; if($suffix) { $url .= '.'.ltrim($suffix,'.'); } } } if($domain) { $url = 'http://'.$domain.$url; }else { $url = "http://" . $_SERVER['HTTP_HOST'] . ($_SERVER['SERVER_PORT'] == 80 ? '' : ':' . $_SERVER['SERVER_PORT']) . $url; } if($redirect) redirect($url); else return $url; } function redirect($url, $time = 0, $msg = '') { $url = str_replace(array("\n", "\r"), '', $url); if (empty($msg)) $msg = "系统将在{$time}秒之后自动跳转到{$url}！"; if (!headers_sent()) { if (0 === $time) { header('Location: ' . $url); } else { header("refresh:{$time};url={$url}"); echo($msg); } exit(); } else { $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>"; if ($time != 0) $str .= $msg; exit($str); } } function S($name, $value = '', $expire = null, $type = '', $options = null) { static $_cache = array(); $cache = Cache::getInstance($type, $options); if ('' !== $value) { if (is_null($value)) { $result = $cache->rm($name); if ($result) unset($_cache[$type . '_' . $name]); return $result; }else { $cache->set($name, $value, $expire); $_cache[$type . '_' . $name] = $value; } return; } if (isset($_cache[$type . '_' . $name])) return $_cache[$type . '_' . $name]; $value = $cache->get($name); $_cache[$type . '_' . $name] = $value; return $value; } function F($name, $value = '', $path = DATA_PATH) { static $_cache = array(); $filename = $path . $name . '.php'; if ('' !== $value) { if (is_null($value)) { return unlink($filename); } else { $dir = dirname($filename); if (!is_dir($dir)) mkdir($dir); $_cache[$name] = $value; return file_put_contents($filename, strip_whitespace("<?php\nreturn " . var_export($value, true) . ";\n?>")); } } if (isset($_cache[$name])) return $_cache[$name]; if (is_file($filename)) { $value = include $filename; $_cache[$name] = $value; } else { $value = false; } return $value; } function get_instance_of($name, $method = '', $args = array()) { static $_instance = array(); $identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args); if (!isset($_instance[$identify])) { if (class_exists($name)) { $o = new $name(); if (method_exists($o, $method)) { if (!empty($args)) { $_instance[$identify] = call_user_func_array(array(&$o, $method), $args); } else { $_instance[$identify] = $o->$method(); } } else $_instance[$identify] = $o; } else halt(L('_CLASS_NOT_EXIST_') . ':' . $name); } return $_instance[$identify]; } function to_guid_string($mix) { if (is_object($mix) && function_exists('spl_object_hash')) { return spl_object_hash($mix); } elseif (is_resource($mix)) { $mix = get_resource_type($mix) . strval($mix); } else { $mix = serialize($mix); } return md5($mix); } function xml_encode($data, $encoding = 'utf-8', $root = 'think') { $xml = '<?xml version="1.0" encoding="' . $encoding . '"?>'; $xml.= '<' . $root . '>'; $xml.= data_to_xml($data); $xml.= '</' . $root . '>'; return $xml; } function data_to_xml($data) { $xml = ''; foreach ($data as $key => $val) { is_numeric($key) && $key = "item id=\"$key\""; $xml.="<$key>"; $xml.= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val; list($key, ) = explode(' ', $key); $xml.="</$key>"; } return $xml; } function session($name, $value = '') { $prefix = C('SESSION_PREFIX'); if (is_array($name)) { if (isset($name['prefix'])) C('SESSION_PREFIX', $name['prefix']); if (isset($_REQUEST[C('VAR_SESSION_ID')])) { session_id($_REQUEST[C('VAR_SESSION_ID')]); } elseif (isset($name['id'])) { session_id($name['id']); } ini_set('session.auto_start', 0); if (isset($name['name'])) session_name($name['name']); if (isset($name['path'])) session_save_path($name['path']); if (isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']); if (isset($name['expire'])) ini_set('session.gc_maxlifetime', $name['expire']); if (isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid'] ? 1 : 0); if (isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies'] ? 1 : 0); if (isset($name['type'])) C('SESSION_TYPE', $name['type']); if (C('SESSION_TYPE')) { $class = 'Session' . ucwords(strtolower(C('SESSION_TYPE'))); if (require_cache(EXTEND_PATH . 'Driver/Session/' . $class . '.class.php')) { $hander = new $class(); $hander->execute(); } else { throw_exception(L('_CLASS_NOT_EXIST_') . ': ' . $class); } } if (C('SESSION_AUTO_START')) session_start(); }elseif ('' === $value) { if (0 === strpos($name, '[')) { if ('[pause]' == $name) { session_write_close(); } elseif ('[start]' == $name) { session_start(); } elseif ('[destroy]' == $name) { $_SESSION = array(); session_unset(); session_destroy(); } elseif ('[regenerate]' == $name) { session_regenerate_id(); } } elseif (0 === strpos($name, '?')) { $name = substr($name, 1); if ($prefix) { return isset($_SESSION[$prefix][$name]); } else { return isset($_SESSION[$name]); } } elseif (is_null($name)) { if ($prefix) { unset($_SESSION[$prefix]); } else { $_SESSION = array(); } } elseif ($prefix) { return $_SESSION[$prefix][$name]; } else { return $_SESSION[$name]; } } elseif (is_null($value)) { if ($prefix) { unset($_SESSION[$prefix][$name]); } else { unset($_SESSION[$name]); } } else { if ($prefix) { if (!is_array($_SESSION[$prefix])) { $_SESSION[$prefix] = array(); } $_SESSION[$prefix][$name] = $value; } else { $_SESSION[$name] = $value; } } } function cookie($name, $value = '', $option = null) { $config = array( 'prefix' => C('COOKIE_PREFIX'), 'expire' => C('COOKIE_EXPIRE'), 'path' => C('COOKIE_PATH'), 'domain' => C('COOKIE_DOMAIN'), ); if (!empty($option)) { if (is_numeric($option)) $option = array('expire' => $option); elseif (is_string($option)) parse_str($option, $option); $config = array_merge($config, array_change_key_case($option)); } if (is_null($name)) { if (empty($_COOKIE)) return; $prefix = empty($value) ? $config['prefix'] : $value; if (!empty($prefix)) { foreach ($_COOKIE as $key => $val) { if (0 === stripos($key, $prefix)) { setcookie($key, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$key]); } } } return; } $name = $config['prefix'] . $name; if ('' === $value) { return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; } else { if (is_null($value)) { setcookie($name, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$name]); } else { $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0; setcookie($name, $value, $expire, $config['path'], $config['domain']); $_COOKIE[$name] = $value; } } } function load_ext_file() { if (C('LOAD_EXT_FILE')) { $files = explode(',', C('LOAD_EXT_FILE')); foreach ($files as $file) { $file = COMMON_PATH . $file . '.php'; if (is_file($file)) include $file; } } if (C('LOAD_EXT_CONFIG')) { $configs = C('LOAD_EXT_CONFIG'); if (is_string($configs)) $configs = explode(',', $configs); foreach ($configs as $key => $config) { $file = CONF_PATH . $config . '.php'; if (is_file($file)) { is_numeric($key) ? C(include $file) : C($key, include $file); } } } } function get_client_ip() { static $ip = NULL; if ($ip !== NULL) return $ip; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown', $arr); if (false !== $pos) unset($arr[$pos]); $ip = trim($arr[0]); }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0'; return $ip; } function send_http_status($code) { static $_status = array( 200 => 'OK', 301 => 'Moved Permanently', 302 => 'Moved Temporarily ', 400 => 'Bad Request', 403 => 'Forbidden', 404 => 'Not Found', 500 => 'Internal Server Error', 503 => 'Service Unavailable', ); if (isset($_status[$code])) { header('HTTP/1.1 ' . $code . ' ' . $_status[$code]); header('Status:' . $code . ' ' . $_status[$code]); } } function url_compare($url, $route) { ksort($url); $url_keys = array_keys($url); ksort($route); $route_keys = array_keys($route); if ($url['a'] != $route['a'] || $url['m'] != $route['m'] || $url_keys != $route_keys) { return false; } else { return true; } } function parseUrl($url) { $var = array(); if (false !== strpos($url, '?')) { $info = parse_url($url); $path = explode('/', $info['path']); parse_str($info['query'], $var); } elseif (strpos($url, '/')) { $path = explode('/', $url); } else { parse_str($url, $var); } if (isset($path)) { $var[C('VAR_ACTION')] = array_pop($path); if (!empty($path)) { $var[C('VAR_MODULE')] = array_pop($path); } if (!empty($path)) { $var[C('VAR_GROUP')] = array_pop($path); } } return $var; } class Log { const EMERG = 'EMERG'; const ALERT = 'ALERT'; const CRIT = 'CRIT'; const ERR = 'ERR'; const WARN = 'WARN'; const NOTICE = 'NOTIC'; const INFO = 'INFO'; const DEBUG = 'DEBUG'; const SQL = 'SQL'; const SYSTEM = 0; const MAIL = 1; const FILE = 3; const SAPI = 4; static $log = array(); static $format = '[ c ]'; static function record($message,$level=self::ERR,$record=false) { if($record || strpos(C('LOG_LEVEL'),$level)) { $now = date(self::$format); self::$log[] = "{$now} ".$_SERVER['REQUEST_URI']." | {$level}: {$message}\r\n"; } } static function save($type='',$destination='',$extra='') { $type = $type?$type:C('LOG_TYPE'); if(self::FILE == $type) { if(empty($destination)) $destination = LOG_PATH.date('y_m_d').'.log'; if(is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination) ) rename($destination,dirname($destination).'/'.time().'-'.basename($destination)); }else{ $destination = $destination?$destination:C('LOG_DEST'); $extra = $extra?$extra:C('LOG_EXTRA'); } error_log(implode('',self::$log), $type,$destination ,$extra); self::$log = array(); } static function write($message,$level=self::ERR,$type='',$destination='',$extra='') { $now = date(self::$format); $type = $type?$type:C('LOG_TYPE'); if(self::FILE == $type) { if(empty($destination)) $destination = LOG_PATH.date('y_m_d').'.log'; if(is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination) ) rename($destination,dirname($destination).'/'.time().'-'.basename($destination)); }else{ $destination = $destination?$destination:C('LOG_DEST'); $extra = $extra?$extra:C('LOG_EXTRA'); } error_log("{$now} ".$_SERVER['REQUEST_URI']." | {$level}: {$message}\r\n", $type,$destination,$extra ); } } class Dispatcher { static public function dispatch() { $urlMode = C('URL_MODEL'); if(!empty($_GET[C('VAR_PATHINFO')])) { $_SERVER['PATH_INFO'] = $_GET[C('VAR_PATHINFO')]; unset($_GET[C('VAR_PATHINFO')]); } if($urlMode == URL_COMPAT ){ define('PHP_FILE',_PHP_FILE_.'?'.C('VAR_PATHINFO').'='); }elseif($urlMode == URL_REWRITE ) { $url = dirname(_PHP_FILE_); if($url == '/' || $url == '\\') $url = ''; define('PHP_FILE',$url); }else { define('PHP_FILE',_PHP_FILE_); } if(C('APP_SUB_DOMAIN_DEPLOY')) { $rules = C('APP_SUB_DOMAIN_RULES'); $subDomain = strtolower(substr($_SERVER['HTTP_HOST'],0,strpos($_SERVER['HTTP_HOST'],'.'))); define('SUB_DOMAIN',$subDomain); if($subDomain && isset($rules[$subDomain])) { $rule = $rules[$subDomain]; }elseif(isset($rules['*'])){ if('www' != $subDomain && !in_array($subDomain,C('APP_SUB_DOMAIN_DENY'))) { $rule = $rules['*']; } } if(!empty($rule)) { $array = explode('/',$rule[0]); $module = array_pop($array); if(!empty($module)) { $_GET[C('VAR_MODULE')] = $module; $domainModule = true; } if(!empty($array)) { $_GET[C('VAR_GROUP')] = array_pop($array); $domainGroup = true; } if(isset($rule[1])) { parse_str($rule[1],$parms); $_GET = array_merge($_GET,$parms); } } } if(empty($_SERVER['PATH_INFO'])) { $types = explode(',',C('URL_PATHINFO_FETCH')); foreach ($types as $type){ if(0===strpos($type,':')) { $_SERVER['PATH_INFO'] = call_user_func(substr($type,1)); break; }elseif(!empty($_SERVER[$type])) { $_SERVER['PATH_INFO'] = (0 === strpos($_SERVER[$type],$_SERVER['SCRIPT_NAME']))? substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME'])) : $_SERVER[$type]; break; } } } $depr = C('URL_PATHINFO_DEPR'); if(!empty($_SERVER['PATH_INFO'])) { if(C('URL_HTML_SUFFIX')) { $_SERVER['PATH_INFO'] = preg_replace('/\.'.trim(C('URL_HTML_SUFFIX'),'.').'$/i', '', $_SERVER['PATH_INFO']); } if(!self::routerCheck()){ $paths = explode($depr,trim($_SERVER['PATH_INFO'],'/')); $_GET[C('VAR_URL_PARAMS')] = $paths; $var = array(); if (C('APP_GROUP_LIST') && !isset($_GET[C('VAR_GROUP')])){ $var[C('VAR_GROUP')] = in_array(strtolower($paths[0]),explode(',',strtolower(C('APP_GROUP_LIST'))))? array_shift($paths) : ''; if(C('APP_GROUP_DENY') && in_array(strtolower($var[C('VAR_GROUP')]),explode(',',strtolower(C('APP_GROUP_DENY'))))) { exit; } } if(!isset($_GET[C('VAR_MODULE')])) { $var[C('VAR_MODULE')] = array_shift($paths); } $var[C('VAR_ACTION')] = array_shift($paths); $res = preg_replace('@(\w+)'.$depr.'([^'.$depr.'\/]+)@e', '$var[\'\\1\']=\'\\2\';', implode($depr,$paths)); $_GET = array_merge($var,$_GET); } define('__INFO__',$_SERVER['PATH_INFO']); } if (C('APP_GROUP_LIST')) { define('GROUP_NAME', self::getGroup(C('VAR_GROUP'))); } define('MODULE_NAME',self::getModule(C('VAR_MODULE'))); define('ACTION_NAME',self::getAction(C('VAR_ACTION'))); define('__SELF__',strip_tags($_SERVER['REQUEST_URI'])); define('__APP__',strip_tags(PHP_FILE)); $module = defined('P_MODULE_NAME')?P_MODULE_NAME:MODULE_NAME; if(defined('GROUP_NAME')) { define('__GROUP__',(!empty($domainGroup) || strtolower(GROUP_NAME) == strtolower(C('DEFAULT_GROUP')) )?__APP__ : __APP__.'/'.GROUP_NAME); define('__URL__',!empty($domainModule)?__GROUP__.$depr : __GROUP__.$depr.$module); }else{ define('__URL__',!empty($domainModule)?__APP__.'/' : __APP__.'/'.$module); } define('__ACTION__',__URL__.$depr.ACTION_NAME); $_REQUEST = array_merge($_POST,$_GET); } static public function routerCheck() { $return = false; tag('route_check',$return); return $return; } static private function getModule($var) { $module = (!empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE')); unset($_GET[$var]); if(C('URL_CASE_INSENSITIVE')) { define('P_MODULE_NAME',strtolower($module)); $module = ucfirst(parse_name(P_MODULE_NAME,1)); } return strip_tags($module); } static private function getAction($var) { $action = !empty($_POST[$var]) ? $_POST[$var] : (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_ACTION')); unset($_POST[$var],$_GET[$var]); define('P_ACTION_NAME',$action); return strip_tags(C('URL_CASE_INSENSITIVE')?strtolower($action):$action); } static private function getGroup($var) { $group = (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_GROUP')); unset($_GET[$var]); return strip_tags(C('URL_CASE_INSENSITIVE') ?ucfirst(strtolower($group)):$group); } } class App { static public function init() { date_default_timezone_set(C('DEFAULT_TIMEZONE')); load_ext_file(); Dispatcher::dispatch(); if(defined('GROUP_NAME')) { if(is_file(CONF_PATH.GROUP_NAME.'/config.php')) C(include CONF_PATH.GROUP_NAME.'/config.php'); if(is_file(COMMON_PATH.GROUP_NAME.'/function.php')) include COMMON_PATH.GROUP_NAME.'/function.php'; } $templateSet = C('DEFAULT_THEME'); if(C('TMPL_DETECT_THEME')) { $t = C('VAR_TEMPLATE'); if (isset($_GET[$t])){ $templateSet = $_GET[$t]; }elseif(cookie('think_template')){ $templateSet = cookie('think_template'); } if(!is_dir(TMPL_PATH.$templateSet)) $templateSet = C('DEFAULT_THEME'); cookie('think_template',$templateSet); } define('THEME_NAME', $templateSet); $group = defined('GROUP_NAME')?GROUP_NAME.'/':''; define('THEME_PATH', TMPL_PATH.$group.(THEME_NAME?THEME_NAME.'/':'')); define('APP_TMPL_PATH',__ROOT__.'/'.APP_NAME.(APP_NAME?'/':'').basename(TMPL_PATH).'/'.$group.(THEME_NAME?THEME_NAME.'/':'')); C('TEMPLATE_NAME',THEME_PATH.MODULE_NAME.(defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/').ACTION_NAME.C('TMPL_TEMPLATE_SUFFIX')); C('CACHE_PATH',CACHE_PATH.$group); return ; } static public function exec() { if(!preg_match('/^[A-Za-z_0-9]+$/',MODULE_NAME)){ $module = false; }else{ $group = defined('GROUP_NAME') ? GROUP_NAME.'/' : ''; $module = A($group.MODULE_NAME); } if(!$module) { if(function_exists('__hack_module')) { $module = __hack_module(); if(!is_object($module)) { return ; } }else{ $module = A('Empty'); if(!$module){ $msg = L('_MODULE_NOT_EXIST_').MODULE_NAME; if(APP_DEBUG) { throw_exception($msg); }else{ if(C('LOG_EXCEPTION_RECORD')) Log::write($msg); send_http_status(404); exit; } } } } $action = ACTION_NAME; tag('action_name',$action); if (method_exists($module,'_before_'.$action)) { call_user_func(array(&$module,'_before_'.$action)); } call_user_func(array(&$module,$action)); if (method_exists($module,'_after_'.$action)) { call_user_func(array(&$module,'_after_'.$action)); } return ; } static public function run() { tag('app_init'); App::init(); tag('app_begin'); session(C('SESSION_OPTIONS')); G('initTime'); App::exec(); tag('app_end'); if(C('LOG_RECORD')) Log::save(); return ; } } abstract class Action { protected $view = null; private $name = ''; public function __construct() { tag('action_begin'); $this->view = Think::instance('View'); if(method_exists($this,'_initialize')) $this->_initialize(); } protected function getActionName() { if(empty($this->name)) { $this->name = substr(get_class($this),0,-6); } return $this->name; } protected function isAjax() { if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) { if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])) return true; } if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) return true; return false; } protected function display($templateFile='',$charset='',$contentType='') { $this->view->display($templateFile,$charset,$contentType); } protected function fetch($templateFile='') { return $this->view->fetch($templateFile); } protected function buildHtml($htmlfile='',$htmlpath='',$templateFile='') { $content = $this->fetch($templateFile); $htmlpath = !empty($htmlpath)?$htmlpath:HTML_PATH; $htmlfile = $htmlpath.$htmlfile.C('HTML_FILE_SUFFIX'); if(!is_dir(dirname($htmlfile))) mk_dir(dirname($htmlfile)); if(false === file_put_contents($htmlfile,$content)) throw_exception(L('_CACHE_WRITE_ERROR_').':'.$htmlfile); return $content; } protected function assign($name,$value='') { $this->view->assign($name,$value); } public function __set($name,$value) { $this->view->assign($name,$value); } public function __get($name) { return $this->view->get($name); } public function __call($method,$args) { if( 0 === strcasecmp($method,ACTION_NAME)) { if(method_exists($this,'_empty')) { $this->_empty($method,$args); }elseif(file_exists_case(C('TEMPLATE_NAME'))){ $this->display(); }elseif(function_exists('__hack_action')) { __hack_action(); }elseif(APP_DEBUG) { throw_exception(L('_ERROR_ACTION_').ACTION_NAME); }else{ if(C('LOG_EXCEPTION_RECORD')) Log::write(L('_ERROR_ACTION_').ACTION_NAME); send_http_status(404); exit; } }else{ switch(strtolower($method)) { case 'ispost': case 'isget': case 'ishead': case 'isdelete': case 'isput': return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2)); case '_get': $input =& $_GET;break; case '_post':$input =& $_POST;break; case '_put': parse_str(file_get_contents('php://input'), $input);break; case '_request': $input =& $_REQUEST;break; case '_session': $input =& $_SESSION;break; case '_cookie': $input =& $_COOKIE;break; case '_server': $input =& $_SERVER;break; case '_globals': $input =& $GLOBALS;break; default: throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } if(isset($input[$args[0]])) { $data = $input[$args[0]]; $fun = $args[1]?$args[1]:C('DEFAULT_FILTER'); $data = $fun($data); }else{ $data = isset($args[2])?$args[2]:NULL; } return $data; } } protected function error($message,$jumpUrl='',$ajax=false) { $this->dispatchJump($message,0,$jumpUrl,$ajax); } protected function success($message,$jumpUrl='',$ajax=false) { $this->dispatchJump($message,1,$jumpUrl,$ajax); } protected function ajaxReturn($data,$info='',$status=1,$type='') { $result = array(); $result['status'] = $status; $result['info'] = $info; $result['data'] = $data; if(method_exists($this,'ajaxAssign')) $this->ajaxAssign($result); if(empty($type)) $type = C('DEFAULT_AJAX_RETURN'); if(strtoupper($type)=='JSON') { header('Content-Type:text/html; charset=utf-8'); exit(json_encode($result)); }elseif(strtoupper($type)=='XML'){ header('Content-Type:text/xml; charset=utf-8'); exit(xml_encode($result)); }elseif(strtoupper($type)=='EVAL'){ header('Content-Type:text/html; charset=utf-8'); exit($data); }else{ } } protected function redirect($url,$params=array(),$delay=0,$msg='') { $url = U($url,$params); redirect($url,$delay,$msg); } private function dispatchJump($message,$status=1,$jumpUrl='',$ajax=false) { if($ajax || $this->isAjax()) $this->ajaxReturn($ajax,$message,$status); if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl); $this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_')); if($this->view->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();'); $this->assign('status',$status); C('HTML_CACHE_ON',false); if($status) { $this->assign('message',$message); if(!$this->view->get('waitSecond')) $this->assign('waitSecond','1'); if(!$this->view->get('jumpUrl')) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]); $this->display(C('TMPL_ACTION_SUCCESS')); exit; }else{ $this->assign('error',$message); if(!$this->view->get('waitSecond')) $this->assign('waitSecond','3'); if(!$this->view->get('jumpUrl')) $this->assign('jumpUrl',"javascript:history.back(-1);"); $this->display(C('TMPL_ACTION_ERROR')); exit ; } } public function __destruct() { if(C('LOG_RECORD')) Log::save(); tag('action_end'); } } class View { protected $tVar = array(); public function assign($name,$value=''){ if(is_array($name)) { $this->tVar = array_merge($this->tVar,$name); }elseif(is_object($name)){ foreach($name as $key =>$val) $this->tVar[$key] = $val; }else { $this->tVar[$name] = $value; } } public function get($name){ if(isset($this->tVar[$name])) return $this->tVar[$name]; else return false; } public function getAllVar(){ return $this->tVar; } public function traceVar(){ foreach ($this->tVar as $name=>$val){ dump($val,1,'['.$name.']<br/>'); } } public function display($templateFile='',$charset='',$contentType='') { G('viewStartTime'); tag('view_begin',$templateFile); $content = $this->fetch($templateFile); $this->show($content,$charset,$contentType); tag('view_end'); } public function show($content,$charset='',$contentType=''){ if(empty($charset)) $charset = C('DEFAULT_CHARSET'); if(empty($contentType)) $contentType = C('TMPL_CONTENT_TYPE'); header('Content-Type:'.$contentType.'; charset='.$charset); header('Cache-control: private'); header('X-Powered-By:ThinkPHP'); echo $content; } public function fetch($templateFile='') { tag('view_template',$templateFile); if(!is_file($templateFile)) return NULL; ob_start(); ob_implicit_flush(0); if('php' == strtolower(C('TMPL_ENGINE_TYPE'))) { extract($this->tVar, EXTR_OVERWRITE); include $templateFile; }else{ $params = array('var'=>$this->tVar,'file'=>$templateFile); tag('view_parse',$params); } $content = ob_get_clean(); tag('view_filter',$content); return $content; } } function delDirFile($path,$arr){ if(is_array($arr)){ foreach($arr as $v){ $delPath = $path.'/'.$v; $allFile = scandir($delPath); foreach($allFile as $val){ if($val != '.' || $val != '..'){ $delfile = $delPath.'/'.$val; unlink($delfile); } } rmdir($delPath); } }else{ $delfile = $path.'/'.$arr; unlink($delfile); } } function delCache($dir){ $handle=@opendir($dir); while ($file = @readdir($handle)) { $bdir=$dir.'/'.$file; if (filetype($bdir)=='dir') { if($file!='.' && $file!='..') delCache($bdir); } else { @unlink($bdir); } } closedir($handle); @rmdir($dir); return true; } function deleteCacheData($dir){ $fileArr = file_list($dir); foreach($fileArr as $file) { if(strstr($file,"Logs")==false) { @unlink($file); } } $fileList = array(); } function file_list($path) { global $fileList; if ($handle = opendir($path)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { if (is_dir($path."/".$file)) { file_list($path."/".$file); } else { $fileList[] = $path."/".$file; } } } } return $fileList; } function url_parse($url){ $rs = preg_match("/^(http:\/\/|https:\/\/)/", $url, $match); if (intval($rs)==0) { $url = "http://".$url; } return $url; } function uimg($img){ if(empty($img)){ return SITE_ROOT."data/user/avatar.gif"; } return $img; } function gmtTime() { return date('YmdHis'); } function IsTwoArray($array){ return count($array)==count($array, 1); } function ReplaceKeywords($content) { if (empty($content) ) { return($content); } if(file_exists('./data/word.txt')){ $str=file_get_contents('./data/word.txt'); $arrKeywords=explode(',', $str); $array_keywords=array(); foreach ($arrKeywords as $key=>$value){ $array_keywords[]=explode('|', $value); } foreach($array_keywords as $arr) { if (strpos($content, $arr[0]) > -1 ) { $content = preg_replace("/" . $arr[0] . "/i", $arr[1], $content); $arrTemp[] = $arr; } } return $content; } else{ return $content; } } function fanli12($username,$commission,$cashback_rate,$integralback_rate){ } function cashback($commission,$cashback_rate,$integralback_rate){ $cashback=array(); $cashback['cacheback']=round($commission*$cashback_rate/100,2); $cashback['integralback']=round($commission*$integralback_rate/100,2); return $cashback; } function cashback_jifenbao($commission,$fanxian_bili,$cashback_rate,$integralback_rate){ $cashback=array(); $cashback['cacheback']=round($commission*$cashback_rate*$fanxian_bili/100,2); $cashback['integralback']=round($commission*$integralback_rate/100,2); return $cashback; } function setFormString($_string) { if (!get_magic_quotes_gpc()) { if (is_array($_string)) { foreach ($_string as $_key=>$_value) { $_string[$_key] = setFormString($_value); } } else { return addslashes($_string); } } return $_string; } function setObjFormItem($_data, $_key, $_value) { $_items = array(); if (is_array($_data)) { foreach ($_data as $_v) { $_items[$_v->$_key] = $_v->$_value; } } return $_items; } function setArrayFormItem($_data, $_key, $_value) { $_items = array(); if (is_array($_data)) { foreach ($_data as $_v) { $_items[$_v[$_key]] = $_v[$_value]; } } return $_items; } function fanli($username, $fxje, $tgje, $order_code, $merchant_id) { if (JIFENOPEN == 1 && JIFENBL > 0) { $jifen = round($fxje * JIFENBL); if ($jifen > 0) { $msg_tabao_jifen = $jifen . "积分！"; } } else { $jifen = 0; } $field_arr = array ( 'money' => $fxje, 'jifen' => $jifen, 'dengji' => 1 ); update_sql('user', $field_arr, "ddusername='$username'", 1); $title = '您获得了新的商城交易返现！'; $trade_id = $order_code; $msg_tabao = "您获得了新的交易返现，" . $merchant_id . "商城订单号" . $order_code . "返现金额" . $fxje . '！' . $msg_tabao_jifen; $filed_arr = array ( 'title' => $title, 'content' => $msg_tabao, 'addtime' => date('Y-m-d H:i:s' ), 'see' => 0, 'ddusername' => $ddusername, 'senduser' => '网站客服'); insert_one_sql("msg", $filed_arr); $shijian = "商城交易返现"; $memo = $merchant_id . "交易号$order_code"; $filed_arr = array ( 'ddusername' => $ddusername, 'shijian' => $shijian, 'addtime' => date('Y-m-d H:i:s' ), 'je' => $fxje, 'jifen' => $jifen, 'memo' => $memo); insert_one_sql("mingxi", $filed_arr); $tjrid = sel_sql("user", "tjr", "ddusername='$ddusername'"); if ($tjrid > 0) { $tjrname = sel_sql("user", "ddusername", "Id='$tjrid'"); $field_arr = array ( 'money' => $tgje ); update_sql("user", $field_arr, "Id='$tjrid'", 1); $title = '您获得了新的推广佣金！'; $msg_taobaotuiguang = "您获得了新的推广佣金" . $tgje; $filed_arr = array ( 'title' => $title, 'content' => $msg_taobaotuiguang, 'addtime' => date('Y-m-d H:i:s' ), 'see' => 0, 'ddusername' => $tjrname, 'senduser' => '网站客服'); insert_one_sql("msg", $filed_arr); $shijian = "推广佣金"; $memo = "交易人$ddusername"; $filed_arr = array ( 'ddusername' => $tjrname, 'shijian' => $shijian, 'addtime' => date('Y-m-d H:i:s' ), 'je' => $tgje, 'memo' => $memo); insert_one_sql("mingxi", $filed_arr); } } function banip($value1,$value2){ $ban_range_low=ip2long($value1); $ban_range_up=ip2long($value2); $ip=ip2long($_SERVER["REMOTE_ADDR"]); if ($ip>=$ban_range_low && $ip<=$ban_range_up) { echo "对不起,您的IP在被禁止的IP段之中，禁止访问！"; exit(); } } function getBanip(){ if(file_exists('./data/banip_config_inc.php')){ $banip=@file_get_contents('./data/banip_config_inc.php'); $banip=unserialize($banip); return $banip; } else{ return false; } } function getUserFace($uid,$type='s'){ $array = array("80"=>"m_","60"=>"z_","35"=>"s_"); if($type=='all'){ foreach($array as $k=>$v){ $facePath = "./data/user/{$uid}/{$v}{$uid}.jpg"; if(file_exists($facePath)){ $face[$k]="./data/user/{$uid}/{$array[$k]}{$uid}.jpg"; }else{ $face[$k] = "./data/user/{$array[$k]}avatar.gif"; } } return $face; }else{ $defaultFace = "./data/user/{$type}_avatar.gif"; $newFace = "./data/user/{$uid}/{$type}_{$uid}.jpg"; if(file_exists($newFace)) $face = "./data/user/{$uid}/{$type}_{$uid}.jpg"; else $face = "./data/user/{$type}_avatar.gif"; return $face; } } function get_object_vars_final($obj){ if(is_object($obj)){ $obj=get_object_vars($obj); } if(is_array($obj)){ foreach ($obj as $key=>$value){ $obj[$key]=get_object_vars_final($value); } } return $obj; } function curl($url, $postFields = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (is_array($postFields) && 0 < count($postFields)) { $postBodyString = ""; foreach ($postFields as $k => $v) { $postBodyString .= "$k=" . urlencode($v) . "&"; } unset($k, $v); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1)); } $reponse = curl_exec($ch); curl_close($ch); return $reponse; } function get_id($url) { $id = 0; $parse = parse_url($url); if (isset($parse['query'])) { parse_str($parse['query'], $params); if (isset($params['id'])) { $id = $params['id']; } elseif (isset($params['item_id'])) { $id = $params['item_id']; } elseif (isset($params['default_item_id'])) { $id = $params['default_item_id']; }elseif(isset($params['mallstItemId'])){ $id = $params['mallstItemId']; }else if(isset($params['num_iid '])){ $id = $params['num_iid']; } } return $id; } function get_diff_date($start_date,$end_date){ $Date_List_a1=explode("-",$start_date); $Date_List_a2=explode("-",$end_date); $d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]); $d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]); $tmp=''; if($d1>$d2){ $tmp=$d2; $d2=$d1; $d1=$tmp; } $Days=round(($d2-$d1)/3600/24); return $Days; } L(array ( '_MODULE_NOT_EXIST_' => '无法加载模块', '_ERROR_ACTION_' => '非法操作', '_LANGUAGE_NOT_LOAD_' => '无法加载语言包', '_TEMPLATE_NOT_EXIST_' => '模板不存在', '_MODULE_' => '模块', '_ACTION_' => '操作', '_ACTION_NOT_EXIST_' => '控制器不存在或者没有定义', '_MODEL_NOT_EXIST_' => '模型不存在或者没有定义', '_VALID_ACCESS_' => '没有权限', '_XML_TAG_ERROR_' => 'XML标签语法错误', '_DATA_TYPE_INVALID_' => '非法数据对象！', '_OPERATION_WRONG_' => '操作出现错误', '_NOT_LOAD_DB_' => '无法加载数据库', '_NOT_SUPPORT_DB_' => '系统暂时不支持数据库', '_NO_DB_CONFIG_' => '没有定义数据库配置', '_NOT_SUPPERT_' => '系统不支持', '_CACHE_TYPE_INVALID_' => '无法加载缓存类型', '_FILE_NOT_WRITEABLE_' => '目录（文件）不可写', '_METHOD_NOT_EXIST_' => '您所请求的方法不存在！', '_CLASS_NOT_EXIST_' => '实例化一个不存在的类！', '_CLASS_CONFLICT_' => '类名冲突', '_TEMPLATE_ERROR_' => '模板引擎错误', '_CACHE_WRITE_ERROR_' => '缓存文件写入失败！', '_TAGLIB_NOT_EXIST_' => '标签库未定义', '_OPERATION_FAIL_' => '操作失败！', '_OPERATION_SUCCESS_' => '操作成功！', '_SELECT_NOT_EXIST_' => '记录不存在！', '_EXPRESS_ERROR_' => '表达式错误', '_TOKEN_ERROR_' => '表单令牌错误', '_RECORD_HAS_UPDATE_' => '记录已经更新', '_NOT_ALLOW_PHP_' => '模板禁用PHP代码', ));C(array ( 'app_status' => 'debug', 'app_file_case' => false, 'app_autoload_path' => '@.TagLib', 'app_tags_on' => true, 'app_sub_domain_deploy' => false, 'app_sub_domain_rules' => array ( ), 'app_sub_domain_deny' => array ( ), 'app_group_list' => '', 'cookie_expire' => 3600, 'cookie_domain' => '', 'cookie_path' => '/', 'cookie_prefix' => '', 'default_app' => '@', 'default_lang' => 'zh-cn', 'default_theme' => 'default', 'default_group' => 'Home', 'default_module' => 'index', 'default_action' => 'index', 'default_charset' => 'utf-8', 'default_timezone' => 'PRC', 'default_ajax_return' => 'JSON', 'default_filter' => 'htmlspecialchars', 'db_type' => 'mysql', 'db_host' => 'localhost', 'db_name' => 'beebuy', 'db_user' => 'root', 'db_pwd' => '123456', 'db_port' => '3306', 'db_prefix' => 'bby', 'db_fieldtype_check' => false, 'db_fields_cache' => true, 'db_charset' => 'utf8', 'db_deploy_type' => 0, 'db_rw_separate' => false, 'db_master_num' => 1, 'db_sql_build_cache' => false, 'db_sql_build_queue' => 'file', 'db_sql_build_length' => 20, 'data_cache_time' => 0, 'data_cache_compress' => false, 'data_cache_check' => false, 'data_cache_type' => 'File', 'data_cache_path' => './admin/Runtime/Temp/', 'data_cache_subdir' => false, 'data_path_level' => 1, 'error_message' => '您浏览的页面暂时发生了错误！请稍后再试～或者联系管理员', 'error_page' => '', 'show_error_msg' => false, 'log_record' => false, 'log_type' => 3, 'log_dest' => '', 'log_extra' => '', 'log_level' => 'EMERG,ALERT,CRIT,ERR', 'log_file_size' => 2097152, 'log_exception_record' => false, 'session_auto_start' => true, 'session_options' => array ( ), 'session_type' => '', 'session_prefix' => '', 'var_session_id' => 'session_id', 'tmpl_content_type' => 'text/html', 'tmpl_action_error' => 'public:error', 'tmpl_action_success' => 'public:success', 'tmpl_exception_file' => './includes/thinkphp/Tpl/think_exception.tpl', 'tmpl_detect_theme' => false, 'tmpl_template_suffix' => '.html', 'tmpl_file_depr' => '/', 'url_case_insensitive' => false, 'url_model' => 0, 'url_pathinfo_depr' => '/', 'url_pathinfo_fetch' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL', 'url_html_suffix' => '', 'var_group' => 'g', 'var_module' => 'm', 'var_action' => 'a', 'var_ajax_submit' => 'ajax', 'var_pathinfo' => 's', 'var_url_params' => '_URL_', 'var_template' => 't', 'ignore_priv_list' => array ( 0 => array ( 'module_name' => 'admin', 'action_list' => array ( 0 => 'ajax_check_username', ), ), 1 => array ( 'module_name' => 'article', 'action_list' => array ( 0 => 'delete_attatch', ), ), 2 => array ( 'module_name' => 'cache', 'action_list' => array ( 0 => 'clearCache', ), ), 3 => array ( 'module_name' => 'focus', 'action_list' => array ( 0 => 'insert', 1 => 'update', 2 => 'status_save', ), ), 4 => array ( 'module_name' => 'index', 'action_list' => array ( ), ), 5 => array ( 'module_name' => 'items', 'action_list' => array ( 0 => 'collect_item', ), ), 6 => array ( 'module_name' => 'items_collect', 'action_list' => array ( 0 => 'collect_success', 1 => 'taobao_collect_jump', ), ), 7 => array ( 'module_name' => 'items_tags_cate', 'action_list' => array ( 0 => 'search', ), ), 8 => array ( 'module_name' => 'public', 'action_list' => array ( ), ), 9 => array ( 'module_name' => 'role', 'action_list' => array ( 0 => 'auth_submit', ), ), 10 => array ( 'module_name' => 'setting', 'action_list' => array ( 0 => 'edit', ), ), ), 'lang_switch_on' => true, 'lang_auto_detect' => true, 'show_page_trace' => false, 'html_cache_on' => false, 'extends' => array ( 'app_init' => array ( ), 'app_begin' => array ( 0 => 'ReadHtmlCache', ), 'route_check' => array ( 0 => 'CheckRoute', ), 'app_end' => array ( ), 'path_info' => array ( ), 'action_begin' => array ( ), 'action_end' => array ( ), 'view_begin' => array ( ), 'view_template' => array ( 0 => 'LocationTemplate', ), 'view_parse' => array ( 0 => 'ParseTemplate', ), 'view_filter' => array ( 0 => 'ContentReplace', 1 => 'TokenBuild', 2 => 'WriteHtmlCache', 3 => 'ShowRuntime', ), 'view_end' => array ( 0 => 'ShowPageTrace', ), ), 'tags' => array ( 'app_begin' => array ( 0 => 'CheckLang', ), ), ));G('loadTime');Think::Start();